package com.example.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.srb.common.exception.Assert;
import com.example.srb.common.result.ResponseEnum;
import com.example.srb.core.enums.*;
import com.example.srb.core.mapper.*;
import com.example.srb.core.pojo.entity.*;
import com.example.srb.core.pojo.vo.BorrowerApprovalVO;
import com.example.srb.core.pojo.vo.BorrowerAttachVO;
import com.example.srb.core.pojo.vo.BorrowerDetailVO;
import com.example.srb.core.pojo.vo.BorrowerVO;
import com.example.srb.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author Helen
 * @since 2021-02-20
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {

    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private BorrowerAttachMapper borrowerAttachMapper;
    @Resource
    private DictService dictService;
    @Resource
    private BorrowerAttachService borrowerAttachService;
    @Resource
    private UserIntegralMapper userIntegralMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBorrowerVOByUserId(BorrowerVO borrowerVO, Long userId) {

        UserInfo userInfo = userInfoMapper.selectById(userId);

        //保存借款人信息
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVO,borrower);
        borrower.setUserId(userId);
        borrower.setName(userInfo.getName());
        borrower.setMobile(userInfo.getMobile());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        baseMapper.insert(borrower);

        //保存附件
        List<BorrowerAttach> borrowerAttachList = borrowerVO.getBorrowerAttachList();
        borrowerAttachList.forEach(borrowerAttach -> {
            borrowerAttach.setBorrowerId(borrower.getId());
            borrowerAttachMapper.insert(borrowerAttach);
        });

        //更新会员状态，更新为认证中
        userInfo.setBorrowAuthStatus(BorrowAuthEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(userInfo);
        
    }

    @Override
    public Integer getBorrowerStatus(Long userId) {
        QueryWrapper<Borrower> wrapper = new QueryWrapper();
        wrapper.select("status").eq("user_id",userId);
        List<Object> objects = baseMapper.selectObjs(wrapper);

        if (objects.size() ==0){
            return BorrowAuthEnum.NO_AUTH.getStatus();
        }

        Integer status = (Integer) objects.get(0);
        return status;
    }

    @Override
    public IPage<Borrower> listPage(Page<Borrower> pageParam, String keyword) {

        if (StringUtils.isBlank(keyword)) {
            return baseMapper.selectPage(pageParam,null);
        }

        QueryWrapper<Borrower> wrapper = new QueryWrapper();
        wrapper.like("name",keyword)
                .or().like("mobile",keyword)
                .or().like("id_card",keyword)
                .orderByDesc("id");
        return baseMapper.selectPage(pageParam, wrapper);
    }

    @Override
    public BorrowerDetailVO getBorrowerDetailVOById(Long id) {
        //获取借款人信息
        Borrower borrower = baseMapper.selectById(id);
        //填充基本借款人信息
        BorrowerDetailVO vo = new BorrowerDetailVO();
        BeanUtils.copyProperties(borrower,vo);
        //婚否
        vo.setMarry(borrower.getMarry()?"是" : "否");
        //性别
        vo.setSex(borrower.getSex() ==1 ? "男" : "女");
        //计算下拉列表选中的内容
        String education = dictService.getNameByParentDictCodeAndValue("education",borrower.getEducation());
        String industry = dictService.getNameByParentDictCodeAndValue("moneyUse",borrower.getIndustry());
        String income = dictService.getNameByParentDictCodeAndValue("income",borrower.getIncome());
        String returnSource = dictService.getNameByParentDictCodeAndValue("returnSource",borrower.getReturnSource());
        String relation = dictService.getNameByParentDictCodeAndValue("relation",borrower.getContactsRelation());
        //设置下拉列表选中内容
        vo.setEducation(education);
        vo.setIndustry(industry);
        vo.setIncome(income);
        vo.setReturnSource(returnSource);
        vo.setContactsRelation(relation);
        //审批状态
        String status = BorrowerStatusEnum.getMsgByStatus(borrower.getStatus());
        vo.setStatus(status);
        //获取附件vo列表
        List<BorrowerAttachVO> attachVOList = borrowerAttachService.selectBorrowerAttachVOList(id);
        vo.setBorrowerAttachVOList(attachVOList);

        return vo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowerApprovalVO borrowerApprovalVO) {
        //修改借款人审核状态 审批完成
        Long borrowerId = borrowerApprovalVO.getBorrowerId();
        Borrower borrower = baseMapper.selectById(borrowerId);
        borrower.setStatus(borrowerApprovalVO.getStatus());
        baseMapper.updateById(borrower);

        Long userId = borrower.getUserId();

        //填充完个人信息，添加上基本积分
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setIntegral(borrowerApprovalVO.getInfoIntegral());
        userIntegral.setContent("借款人个人基本信息");
        userIntegralMapper.insert(userIntegral);

        UserInfo userInfo = userInfoMapper.selectById(userId);
        int curIntegral = userInfo.getIntegral() + borrowerApprovalVO.getInfoIntegral();

        //增加身份证信息的积分
        if (borrowerApprovalVO.getIsCarOk()){
            curIntegral += IntegralEnum.BORROWER_IDCARD.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());
            userIntegralMapper.insert(userIntegral);
        }

        //增加房产信息的积分
        if (borrowerApprovalVO.getIsHouseOk()){
            curIntegral += IntegralEnum.BORROWER_HOUSE.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());
            userIntegralMapper.insert(userIntegral);
        }

        //增加车辆信息的积分
        if (borrowerApprovalVO.getIsCarOk()){
            curIntegral += IntegralEnum.BORROWER_CAR.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_CAR.getMsg());
        }

        userInfo.setIntegral(curIntegral);
        userInfo.setBorrowAuthStatus(borrowerApprovalVO.getStatus());
        userInfoMapper.updateById(userInfo);

    }



}
